//
//  SellerOrderManagementVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/13.
//  Copyright © 2020 cat. All rights reserved.
//

#import "SellerOrderManagementVC.h"
#import "SPPageMenu.h"
#import "SellOrderCell.h"
#import "SellOrderModel.h"
#import "WaitSendGoodsVC.h"
#import "OtherSellOrderDetailVC.h"
#import "RefundDetailVC.h"
@interface SellerOrderManagementVC ()<SPPageMenuDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,sellOrderCellDelegate>
{
    UIView *selectView;
    NSArray *tableArray;
    NSArray *lisetTableArray;

    UITableView *selectTable;

    int selectIndex;
    int pageIndex;
    
    NSString *orderType;
    NSArray *orderArr;

}
@property(nonatomic, strong)NSArray *titles;
@property (nonatomic, strong) SPPageMenu *pageMenu;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *orderTable;

@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSArray *models;

@end

@implementation SellerOrderManagementVC

-(NSArray *)models{
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSDictionary *dic in self.dataArr) {
        SellOrderModel *model = [SellOrderModel modelWithDictionary:dic];
        [array addObject:model];
    }
    _models = array;
    return _models;
}

-(void)getGoodsOrderList{
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"type":orderType,
                          @"p":@(pageIndex),
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    
    [WYNetworking postWithUrl:@"Seller.getGoodsOrderList" Dic:dic Suc:^(int code, id info, NSString *msg) {
        
        [self.orderTable.mj_header endRefreshing];
        [self.orderTable.mj_footer endRefreshing];
        if (code ==0) {
            NSArray *listArr = [[info firstObject]valueForKey:@"list"];
            NSDictionary*typeNumDic = [[info firstObject] valueForKey:@"type_list_nums"];
            
            [self reloadNum:typeNumDic];

            if (pageIndex == 1) {
                [self.dataArr removeAllObjects];

                if (listArr.count < 1) {
                    [PublicView showImgNoData:self.orderTable name:@"shop_无数据" text:YZMsg(@"你还没有相关订单")];
                    [self.orderTable reloadData];
                    return ;
                }else{
                    [PublicView hiddenImgNoData:self.orderTable];
                }

            }
            [self.dataArr addObjectsFromArray:listArr];
            [self.orderTable reloadData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [self.orderTable.mj_header endRefreshing];
            [self.orderTable.mj_footer endRefreshing];

        }];

}
-(void)reloadNum:(NSDictionary *)typeNumDic{
    lisetTableArray = @[YZMsg(@"退款订单"),YZMsg(@"已发货订单"),YZMsg(@"已签收订单"),YZMsg(@"已完成订单"),YZMsg(@"已关闭订单"),YZMsg(@"全部订单")];
    tableArray = @[[NSString stringWithFormat:@"%@%@",YZMsg(@"退款订单"),minstr([typeNumDic valueForKey:@"all_refund_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"已发货订单"),minstr([typeNumDic valueForKey:@"wait_receive_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"已签收订单"),minstr([typeNumDic valueForKey:@"wait_evaluate_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"已完成订单"),minstr([typeNumDic valueForKey:@"finished_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"已关闭订单"),minstr([typeNumDic valueForKey:@"closed_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"全部订单"),minstr([typeNumDic valueForKey:@"all_nums"])]];
    
    
    _titles = @[[NSString stringWithFormat:@"%@%@",YZMsg(@"待发货"),minstr([typeNumDic valueForKey:@"wait_shipment_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"等待退款"),minstr([typeNumDic valueForKey:@"wait_refund_nums"])],
                   [NSString stringWithFormat:@"%@%@",YZMsg(@"待支付"),minstr([typeNumDic valueForKey:@"wait_payment_nums"])],@"其他"];

    [_pageMenu reloadInputViews];
    
    [_pageMenu setTitle:_titles[0] forItemAtIndex:0];
    [_pageMenu setTitle:_titles[1] forItemAtIndex:1];
    [_pageMenu setTitle:_titles[2] forItemAtIndex:2];

    SPPageMenuButtonItem *items = [_pageMenu contentForItemAtIndex:3];
    if ([items.title containsString:YZMsg(@"其他")]) {
        SPPageMenuButtonItem *item2 = [SPPageMenuButtonItem itemWithTitle:[NSString stringWithFormat:@"%@%@",YZMsg(@"其他"),minstr([typeNumDic valueForKey:@"all_nums"])] image:[UIImage imageNamed:@"order_下拉"] imagePosition:SPItemImagePositionRight];
        [_pageMenu setItem:item2 forItemAtIndex:3];
        [self hideBtnClick];

    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.orderTable.mj_header beginRefreshing];
}
-(void)initData{
    //type（订单类型 all 所有订单 wait_payment 待付款 wait_shipment 待发货 wait_refund 待退款 all_refund 全部退款  wait_receive 已发货,待收货 wait_evaluate 已签收,待评价 closed 已关闭 finished 已完成）

    orderArr = @[@"all",@"wait_payment",@"wait_shipment",@"wait_refund",@"all_refund",@"wait_receive",@"wait_evaluate",@"closed",@"finished"];
    
    pageIndex = 1;
    orderType = @"all";
    _titles = @[@"待发货",@"等待退款",@"待支付",@"其他"];
    self.dataArr = [NSMutableArray array];
    tableArray = @[YZMsg(@"退款订单"),YZMsg(@"已发货订单"),YZMsg(@"已签收订单"),YZMsg(@"已完成订单"),YZMsg(@"已关闭订单"),YZMsg(@"全部订单")];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text  = YZMsg(@"订单管理");
    self.view.backgroundColor = RGB(250, 250, 250);
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);
    [self.view addSubview:self.orderTable];

    [self initData];
    
    _pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, 40) trackerStyle:SPPageMenuTrackerStyleLineAttachment];
    [_pageMenu setItems:self.titles selectedItemIndex:self.selectIndex];
    
    if (self.selectIndex == 3) {
        SPPageMenuButtonItem *item2 = [SPPageMenuButtonItem itemWithTitle:YZMsg(@"其他") image:[UIImage imageNamed:@"order_下拉"] imagePosition:SPItemImagePositionRight];// YZMsg(@"全部订单")
        [_pageMenu setItem:item2 forItemAtIndex:3];
        [self hideBtnClick];

    }else{
        SPPageMenuButtonItem *item2 = [SPPageMenuButtonItem itemWithTitle:YZMsg(@"其他") image:[UIImage imageNamed:@"order_下拉"] imagePosition:SPItemImagePositionRight];
        [_pageMenu setItem:item2 forItemAtIndex:3];

    }

    _pageMenu.delegate = self;
    _pageMenu.dividingLine.hidden = YES;
    _pageMenu.selectedItemTitleColor = [UIColor blackColor];
    _pageMenu.itemTitleFont = [UIFont systemFontOfSize:12];
    _pageMenu.unSelectedItemTitleColor = UIColor.grayColor;
    _pageMenu.selectedItemTitleFont =  [UIFont systemFontOfSize:14];
    _pageMenu.unSelectedItemTitleFont = [UIFont systemFontOfSize:14];
    _pageMenu.permutationWay = SPPageMenuPermutationWayNotScrollEqualWidths;
    _pageMenu.backgroundColor = RGB(235, 235, 235);
    _pageMenu.bridgeScrollView = self.scrollView;
    _pageMenu.tracker.backgroundColor = Pink_Cor;
    [self.view addSubview:_pageMenu];

    
    [self getGoodsOrderList];

}
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedAtIndex:(NSInteger)index {
    NSLog(@"sssssss::::%zd",index);
    switch (index) {
        case 0:
            orderType = orderArr[2];
            [self hideBtnClick];
            [self changeItemtitle];
            [self.orderTable.mj_header beginRefreshing];

            break;
        case 1:
            orderType = orderArr[3];
            [self hideBtnClick];
            [self changeItemtitle];
            [self.orderTable.mj_header beginRefreshing];

            break;
        case 2:
            orderType = orderArr[1];
            [self hideBtnClick];
            [self changeItemtitle];
            [self.orderTable.mj_header beginRefreshing];

            break;
        case 3:{
            SPPageMenuButtonItem *item =[_pageMenu itemAtIndex:3];
            if ([item.title containsString:YZMsg(@"其他")]) {
                [self.dataArr removeAllObjects];
                [self.orderTable reloadData];
            }
            if (!selectView) {
                [self creatSelectView];
            }else{
                [self showSelectTable];
            }
        }
            break;

        default:
            break;
    }
}
-(void)changeItemtitle{
    SPPageMenuButtonItem *item2 = [SPPageMenuButtonItem itemWithTitle:YZMsg(@"其他") image:[UIImage imageNamed:@"order_下拉"] imagePosition:SPItemImagePositionRight];
    [_pageMenu setItem:item2 forItemAtIndex:3];

}
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64+statusbarHeight+40, _window_width, _window_height-64-statusbarHeight-40)];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    return  _scrollView;
}

-(UITableView *)orderTable{
    if (!_orderTable) {
        _orderTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight+40, _window_width, _window_height-64-statusbarHeight-40) style:UITableViewStylePlain];
        _orderTable.delegate = self;
        _orderTable.dataSource = self;
        _orderTable.separatorStyle = 0;
        _orderTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            pageIndex = 1;
            [self getGoodsOrderList];
        }];
        _orderTable.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            pageIndex ++;
            [self getGoodsOrderList];
        }];
        _orderTable.backgroundColor = UIColor.whiteColor;
    }
    return _orderTable;
}

#pragma mark - scrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    // 这一步是实现跟踪器时刻跟随scrollView滑动的效果,如果对self.pageMenu.scrollView赋了值，这一步可省
    // [self.pageMenu moveTrackerFollowScrollView:scrollView];
}

#pragma mark ============排列顺序选择页面=============
- (void)creatSelectView{
    selectView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight+40, _window_width, _window_height-64-statusbarHeight-40)];
    selectView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    [self.view addSubview:selectView];

    if (selectIndex != 9999) {
        selectIndex = 0;
    }
    selectTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 0) style:0];
    selectTable.delegate = self;
    selectTable.dataSource = self;
    selectTable.separatorStyle = 0;
    [selectView addSubview:selectTable];
    UIButton *hideBtn = [UIButton buttonWithType:0];
    hideBtn.frame = CGRectMake(0, 240, _window_width, selectView.height-240);
    [hideBtn addTarget:self action:@selector(hideBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selectView addSubview:hideBtn];
    
    [self showSelectTable];
}
- (void)hideBtnClick{
    [UIView animateWithDuration:0.1 animations:^{
        selectTable.frame = CGRectMake(0, 0, _window_width, 0);
    } completion:^(BOOL finished) {
        selectView.hidden = YES;

    }];
    SPPageMenuButtonItem *items = [_pageMenu contentForItemAtIndex:3];
    [items setImage:[UIImage imageNamed:@"order_下拉"]];
    items.title = [items.title stringByReplacingOccurrencesOfString:YZMsg(@"订单") withString:@""];
    [_pageMenu setItem:items forItemAtIndex:3];

}
- (void)showSelectTable{
    selectView.hidden = NO;
    [selectTable reloadData];
    [UIView animateWithDuration:0.1 animations:^{
        selectTable.frame = CGRectMake(0, 0, _window_width, 240);
    }];
    SPPageMenuButtonItem *items = [_pageMenu contentForItemAtIndex:3];
    [items setImage:[UIImage imageNamed:@"order_上拉"]];
    [_pageMenu setItem:items forItemAtIndex:3];

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _orderTable) {
        return 185;
    }else{
        return 40;

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.orderTable) {
        return self.models.count;
    }else{
        return 6;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.orderTable) {
        SellOrderCell *cell = [SellOrderCell cellWithTab:tableView andIndexPath:indexPath];
        cell.model = self.models[indexPath.row];
        cell.delegate = self;
        cell.contentView.backgroundColor = UIColor.whiteColor;
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectClassCELL"];
        if (!cell) {
            cell  = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"selectClassCELL"];
        }
        cell.textLabel.text = lisetTableArray[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor grayColor];
        
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (tableView ==  self.orderTable) {
        SellOrderModel *model = self.models[indexPath.row];
        if ([model.status isEqual:@"1"]) {
            WaitSendGoodsVC *wait = [[WaitSendGoodsVC alloc]init];
            wait.orderModel = model;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:wait animated:YES];
        }else if ([model.status isEqual:@"5"]){
            RefundDetailVC *refund = [[RefundDetailVC alloc]init];
            refund.orderModel = model;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:refund animated:YES];
        } else{
            OtherSellOrderDetailVC *other = [[OtherSellOrderDetailVC alloc]init];
            other.orderModel = model;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:other animated:YES];
        }
    }else{
        SPPageMenuButtonItem *item2 = [SPPageMenuButtonItem itemWithTitle:tableArray[indexPath.row] image:[UIImage imageNamed:@"order_下拉"] imagePosition:SPItemImagePositionRight];
        [_pageMenu setItem:item2 forItemAtIndex:3];
        
        //type（订单类型 all 所有订单 wait_payment 待付款 wait_shipment 待发货 wait_refund 待退款 all_refund 全部退款  wait_receive 已发货,待收货 wait_evaluate 已签收,待评价 closed 已关闭 finished 已完成）

        switch (indexPath.row) {
            case 0:
                orderType = orderArr[4];
                break;
            case 1:
                orderType = orderArr[5];
                break;
            case 2:
                orderType = orderArr[6];
                break;
            case 3:
                orderType = orderArr[8];
                break;
            case 4:
                orderType = orderArr[7];
                break;
            case 5:
                orderType = orderArr[0];
                break;

            default:
                break;
        }
        [self hideBtnClick];
        [self.orderTable.mj_header beginRefreshing];
    }
}
#pragma mark-------删除订单-------------
-(void)cellBtnClickWithModel:(SellOrderModel *)model withTitle:(NSString *)title
{
        UIAlertController *deleteAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"确定删除订单?") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self deleteOrder:model];
        }];
        [deleteAlert addAction:cancle];
        [deleteAlert addAction:sureAction];
        [cancle setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
        [sureAction setValue:Pink_Cor forKey:@"titleTextColor"];

        [self presentViewController:deleteAlert animated:YES completion:nil];
}
-(void)deleteOrder:(SellOrderModel *)model{
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":model.idStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    [WYNetworking postWithUrl:@"Seller.delGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:YZMsg(@"删除成功")];
            [self.orderTable.mj_header beginRefreshing];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];


}
@end
